/**
 * Copyright (c) 2019 AsHacker All rights reserved.
 * <p>
 * http://www.ashacker.com
 * <p>
 * 版权所有，侵权必究！
 */

package io.renren.modules.job.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.utils.MapUtils;
import io.renren.modules.app.constants.StringConstants;
import io.renren.modules.lucky.dao.*;
import io.renren.modules.lucky.entity.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 系统商品周期问题
 * -- 废弃：已过期 flag=1
 * <p>
 * 未开始 flag=2 物品看不到
 * 已开始 flag=3 价格看不到
 * 已结束 flag=4 都可以看到并且用户中奖信息都存在
 * 明日活动 flag=5 准备开始的
 * 未上线已创建 flag=6 看不到
 * 已删除 flag=0 看不到
 * <p>
 * activityTask为spring bean的名称
 *
 * @author Chen chenchen@ashacker.com
 */
@Component("activityTask")
public class ActivityTask implements ITask {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private AppGoodsInfoDao appGoodsInfoDao;

    @Autowired
    private AppGoodsCommentDao appGoodsCommentDao;

    @Autowired
    private AppGoodsAddrDao appGoodsAddrDao;

    @Autowired
    private AppSysNoticeDao appSysNoticeDao;

    @Autowired
    private AppUserAddrDao appUserAddrDao;

    /**
     * 每小时执行一次
     * <p>
     * 未开始商品——》已开始商品：flag=2，再时间范围内的
     * 已开始商品——》未开始商品：
     *
     * @param params 参数，多参数使用JSON数据
     */
    @Override
    @Transactional(readOnly = false)
    public void run(String params) {
        logger.debug("ActivityTask定时任务正在执行，启动参数为：{}", params);
        try {
            AppGoodsInfoEntity infoEntity = new AppGoodsInfoEntity();
            Date date = new Date();
            //1、查询未开始产品flag=2——》flag=3
            int num = appGoodsInfoDao.selectCount(new QueryWrapper<AppGoodsInfoEntity>().eq("goods_flag", 2)
                    .le("start_time", date).ge("end_time", date));
            if (num > 0) {
                logger.info("转化未开始产品——》为开始产品");
                infoEntity.setGoodsFlag(3);
                appGoodsInfoDao.update(infoEntity, new QueryWrapper<AppGoodsInfoEntity>().eq("goods_flag", 2)
                        .le("start_time", date).ge("end_time", date));
            } else {
                logger.info("未有到达活动时间的产品");
            }
            //2、查询已开始产品flag=3——》flag=4
            List<AppGoodsInfoEntity> list2 = appGoodsInfoDao.selectList(new QueryWrapper<AppGoodsInfoEntity>().eq("goods_flag", 3)
                    .le("end_time", date));
            if (list2.size() > 0) {
                logger.info("转化已开始产品——》为结束产品");
                infoEntity.setGoodsFlag(4);
                appGoodsInfoDao.update(infoEntity, new QueryWrapper<AppGoodsInfoEntity>().eq("goods_flag", 3)
                        .le("end_time", date));
                //winUser
                if (StringConstants.winnerFlag == 0)
                    winUser(list2);
            } else {
                logger.info("未有结束活动时间的产品");
            }
            //3、查询明日活动或之后7天准备开始的活动产品flag=5——》flag=2
            List<AppGoodsInfoEntity> list1 = appGoodsInfoDao.queryGoodsListByDay(5, "0", "0");
            if (list1.size() > 0) {
                logger.info("转化明日活动或之后7天准备开始的活动产品——》为未开始产品");
                String ids = "";
                for (AppGoodsInfoEntity infoEntity1 : list1) {
                    ids = infoEntity1.getId() + ",";
                }
                ids = ids.substring(0, ids.length() - 1);
                infoEntity.setGoodsFlag(2);
                appGoodsInfoDao.update(infoEntity, new QueryWrapper<AppGoodsInfoEntity>().eq("goods_flag", 5)
                        .in("id", ids));
            } else {
                logger.info("未开始产品");
            }
            //4、查询已创建未上线产品flag=6——》flag=5
            List<AppGoodsInfoEntity> list = appGoodsInfoDao.queryGoodsListByDay(6, "1", "7");
            if (list.size() > 0) {
                logger.info("转化已创建未上线产品——》为明日活动或之后7天准备开始的活动产品");
                String ids = "";
                for (AppGoodsInfoEntity infoEntity1 : list) {
                    ids = infoEntity1.getId() + ",";
                }
                ids = ids.substring(0, ids.length() - 1);
                infoEntity.setGoodsFlag(5);
                appGoodsInfoDao.update(infoEntity, new QueryWrapper<AppGoodsInfoEntity>().eq("goods_flag", 6)
                        .in("id", ids));
            } else {
                logger.info("未有明日活动或之后7天准备开始的活动产品");
            }
        } catch (Exception e) {
            logger.error("保存信息失败,错误原因:" + e.getMessage(), e);
            e.printStackTrace();
        }
    }

    /**
     * 为每个结束的活动，选一名获奖者
     *
     * @param list
     * @return
     */
    void winUser(List<AppGoodsInfoEntity> list) throws Exception {
        List<AppGoodsCommentEntity> commentEntityList = new ArrayList<AppGoodsCommentEntity>();
        for (AppGoodsInfoEntity infoEntity : list) {
            Map<Integer, Double> map = new HashMap<>();
            commentEntityList = appGoodsCommentDao.selectList(new QueryWrapper<AppGoodsCommentEntity>()
                    .eq("comment_flag", 1)
                    .eq("comment_type", 2)
                    .le("create_time", infoEntity.getEndTime())
                    .ge("create_time", infoEntity.getStartTime())
                    .orderByAsc("create_time"));

            logger.info("获取key:用户id value:价格的map集合");
            for (AppGoodsCommentEntity commentEntity : commentEntityList) {
                double price = Double.parseDouble(commentEntity.getCommentContent()) - Double.parseDouble(infoEntity.getGoodsShowPrice());
                map.put(commentEntity.getUserId(), price);
                logger.info("price:" + price + ",userId:" + commentEntity.getUserId());
            }

            if (!map.isEmpty()) {
                logger.info("获得最小的value值");
                double value = Double.parseDouble(MapUtils.getMinValue(map).toString());
                int userId = 0;
                for (Map.Entry<Integer, Double> m : map.entrySet()) {
                    if (m.getValue().equals(value)) {
                        userId = m.getKey();
                        break;
                    }
                }
                logger.info("value：" + value + " userId：" + userId);

                logger.info("获取用户收货地址");
                AppUserAddrEntity addrEntity = appUserAddrDao.selectOne(new QueryWrapper<AppUserAddrEntity>()
                        .eq("user_id", userId).eq("addr_flag", 1).eq("addr_default", 1));
                if (addrEntity == null || addrEntity.equals("")) {
                    AppSysNoticeEntity noticeEntity = new AppSysNoticeEntity();
                    noticeEntity.setUserId(userId);
                    noticeEntity.setCreateTime(new Date());
                    noticeEntity.setNoticeFlag(1);
                    noticeEntity.setNoticeTitle("中奖了");
                    noticeEntity.setNoticeContent("本期商品，您已猜中，请填写收货地址，我们才可以进行发货。");
                    appSysNoticeDao.insert(noticeEntity);
                }

                logger.info("根据userId设定获奖信息");
                AppGoodsAddrEntity addrEntity1 = new AppGoodsAddrEntity();
                addrEntity1.setUserId(userId);
                addrEntity1.setAddrId(addrEntity.getId());
                Date date = new Date();
                addrEntity1.setCreateTime(date);
                addrEntity1.setUpdateTime(date);
                addrEntity1.setGoodsId(infoEntity.getId());
                appGoodsAddrDao.insert(addrEntity1);
            }
        }
    }

}
